const filesize = require("filesize");
const fs = require("fs");
const path = require("path");

const upload_single = require("./upload-single");

/**
 * 
 * @param {String} full_path must exists
 * @returns {Promise<{ok:Boolean,url:String,msg:String,file_size:String,speed:String}>}
 */
function testUploadSpeed(full_path) {
  return new Promise(async resolve => {
    fs.stat(full_path, async (err, stats) => {
      if (err) {
        return resolve({
          ok: false,
          msg: err.message,
          url: "",
          file_size: "",
          speed: ""
        });
      }
      if (!stats.isFile()) {
        return resolve({
          ok: false,
          msg: `It is not a file ! ${full_path}`,
          url: "",
          file_size: "",
          speed: ""
        });
      }
      let start_time = Date.now();
      console.log("start uploading...", path.basename(full_path));
      let oup = await upload_single.uploadSingle(full_path);
      let end_time = Date.now();
      if (!oup.ok) {
        return resolve({
          ok: false,
          msg: oup.msg,
          url: "",
          file_size: "",
          speed: ""
        });
      }
      let bytes_per_second = stats.size / ((end_time - start_time) / 1000);
      resolve({
        ok: true,
        msg: "ok",
        url: oup.url,
        file_size: filesize(stats.size),
        speed: filesize(bytes_per_second) + "/s"
      })
    })
  })
}


module.exports = {
  testUploadSpeed
}